<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="container">
    <a href="./">首页</a>
    <a href="./about">关于我们</a>
    <a href="./user">用户列表</a>
</div>
<div id="context"></div>
<script>
    class BaseRouter {
        constructor() {
            this.routes = {};
            this._bindPopstate();  // _bindPopstate方法监听浏览器go()和back()触发的popState事件
        }

        route(path, callback) {
            this.routes[path] = callback || function () {
            }
        }

        go(path) {
            window.history.pushState({path}, null, path);
            const cb = this.routes[path];
            if (cb) {
                cb();
            }
        }

        _bindPopstate() {
            window.addEventListener('popstate', e => {
                const path = e.state && e.state.path;
                this.routes[path] && this.routes[path]();
            })
        }
    }

    const Route = new BaseRouter();

    Route.route('./about', () => changeText("关于我们页面"));
    Route.route('./user', () => changeText("用户列表页"));
    Route.route('./', () => changeText("首页"));

    function changeText(arg) {
        document.getElementById('context').innerHTML = arg;
    }

    document.getElementById('container').addEventListener('click', e => {
        if (e.target.tagName === 'A') {
            e.preventDefault();
            Route.go(e.target.getAttribute('href'))
        }
    })
</script>

</body>
</html>